/**
* @depends jquery.ui.js
*/

(function($){

	$.widget( 'ui.widget_flow_genericflow_comment', {
		
		_init: function() {

			this.element.find( 'p' ).morify();
			
			this._initDelete();
			this._initLike();
		},
		
		
		_initDelete: function() {
		
			var $this = this;
			var comment_id = this.element.attr( 'comment_id' );
			var del = $('.Delete.Icon', this.element);
			
			del.tooltip( {
				tip: 'Delete comment'
			} );
			
			del.click( function() {
			
				var dialog = $.window.create()
					.dialog( {
						title: 'Confirmation',
						message: 'Are you sure you want to delete this comment ?',
						icon: $.dialog.icons.warning,
						buttons: {
							yes: function() {
								dialog.dialog( 'close' );
								$.wajax( 'Flow_GenericFlow_Comment_Delete', {
									id: comment_id
								}, function( json ) {
									if( json.status != 'success' ) {
										return false;
									}
									$this.element.slideUp( 'fast', function() {
										var item = $this.element.closest( '.Widget_Flow_GenericFlow_Item' );
										$this.element.parent().remove();
										item.widget_flow_genericflow_item( 'refresh' );
									} );
								} );
							},
							cancel: function() {
								dialog.dialog( 'close' );
							}
						}
					} )
					.dialog( 'open' );
			} );
		},
		
		_initLike: function() {
		
			var comment_id = this.element.attr( 'comment_id' );
			var like = $('h6 span', this.element);
			var likeAction = $('a[action=like]', this.element);
			
			likeAction.toggler( {
				messages: [ 'Like', 'Unlike' ],
				currentIndex: parseInt(likeAction.attr( 'currentIndex' )),
				async: function( index ) {
					$.wajax( 'Flow_GenericFlow_Comment_' + (index ? 'Like' : 'Unlike'), {
						id : comment_id
					}, function( json ) {
						if( json.status != 'success' ) {
							return false;
						}
						like.html( json.content );
						like.triggerHandler( 'like-refresh' );
						likeAction.toggler( 'toggle' );
					} );
				}
			} );
		}
	
	} );

})(jQuery);
